<template>
  <div class="app-container">
    <UserCard name="张三" email="123@gamil.com" avatar-url="src/assets/yinshi.jpg" greeting-message="hello" />
    <UserCard name="李四" email="456@gamil.com" avatar-url="src/assets/yinshi.jpg" />

    <h2>动态的props</h2>
    <UserCard :userObj="userObj" />
    <div class="input-group">
      <input type="text" v-model="newName" placeholder="请输入新的名字">
      <button @click="changeName">确定修改</button>
    </div>

  </div>
</template>

<script setup>
  import { ref, watchEffect } from 'vue'
  import UserCard from './components/UserCard.vue'
  const DEFAULT_USER_OBJ = {
    name: '张三',
    email: '123@gamil.com',
    avatarUrl: 'src/assets/yinshi.jpg',
    age: 18
  }
  // 父组件所维护的一份数据
  const userObj = ref(JSON.parse(localStorage.getItem('userObj')) || DEFAULT_USER_OBJ)
  const newName = ref('')

  // 根据用户输入的新名字
  // 更新 user 这个数据
  function changeName() {
    if (newName.value && window.confirm('你确定要修改姓名嘛？')) {
      userObj.value.name = newName.value.trim()
      newName.value = ''
    }

  }

  //设置监听,默认会执行一遍
  watchEffect(() => {
    //每次userObject变化就存储更新
    localStorage.setItem('userObj', JSON.stringify(userObj.value))
  })
</script>

<style scoped>
  .app-container {
    max-width: 500px;
    margin: auto;
    padding: 20px;
  }

  .input-group {
    display: flex;
    margin-top: 20px;
  }

  input {
    flex: 1;
    padding: 10px;
    margin-right: 10px;
    font-size: 16px;
    border: 1px solid #ddd;
    border-radius: 5px;
  }

  button {
    padding: 10px 15px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 16px;
  }

  button:hover {
    background-color: #0056b3;
  }
</style>
